package com.xbfinal.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xbfinal.reggie.Ulits.ValidateCodeUtils;
import com.xbfinal.reggie.common.R;
import com.xbfinal.reggie.pojo.User;
import com.xbfinal.reggie.service.UserSerice;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
public class Usercontroller {

    @Autowired
    private UserSerice userSerice;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String MyFrom;


    /**
     * 发送验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,
                             HttpSession session){
        log.info("R<String> sendMsg()进来了");
        //获取手机号
        final String phone = user.getPhone();//就不修改实体类了把邮件写进 Phone

        //判断手机号不为空
        if(StringUtils.isNotEmpty(phone)) {
            //生成4位验证码
            final String code =
                    ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println("==========");
            System.out.println(code);//验证码
            System.out.println("==========");
            //***************************************************/
            //创建简单邮件消息
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(MyFrom);//用自己的邮件发
            //谁要接收
            message.setTo(phone);
            //邮件标题
            message.setSubject("验证码");
            //邮件内容
            message.setText("【笑霸final】你的验证码为："+code);//
            try {
                mailSender.send(message);
                //需要保存一下验证码，后面用来验证
                //session.setAttribute(phone, code);

                //将生成的验证码缓存到redis中，并设置有效期5分钟
                redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);

                return R.success("发送成功");
            } catch (MailException e) {
                e.printStackTrace();
                return R.error("短信发送失败");
            }
        }
        return R.error("短信发送失败");
    }

    /**
     * 登陆
     * @param
     * @param session
     * @return
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map map,
                           HttpSession session){

        //获取邮箱和验证码
        final String phone = map.get("phone").toString();
        final String code = map.get("code").toString();
        //获取session的验证码并比对
        //final Object codeInsession = session.getAttribute(phone);

        //从redis中获取缓存的验证码
        Object codeInsession = redisTemplate.opsForValue().get(phone);

        if(codeInsession!=null && codeInsession.equals(code)){
            //登陆成功
            //查数据库，没有就存入数据库
            LambdaQueryWrapper<User> queryWrapper
                    =new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
             User user = userSerice.getOne(queryWrapper);
            if(user == null){
                //新用户 入库
                 user = new User();
                 user.setPhone(phone);
                 user.setStatus(1);
                userSerice.save(user);
            }else if(user.getStatus()==0){
                //账号被禁用
                return R.error("账号被禁用");
            }
            //成功存入session
            session.setAttribute("user",user.getId());

            //如果登陆成功就删除验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }
        return R.error("验证码和手机不匹配");
    }
}
